import React, { useEffect } from "react";
import Button from "../Button";
import message from "../message";
import useStyles from "./useStyles";
import ConditionItem from "./ConditionItem";
import classNames from "classnames";
import Joint from "./components/Joint";
import { getOperatorsByField } from "./utils";

import type {
  NestFilterCondition,
  NestFilterConditions,
  NestFilterJoint,
  NestFilterFields,
  NestFilterChangeHandler,
} from "./type";

export interface ConditionArrayProps {
  seq: number;
  joint: NestFilterJoint;
  conditions: NestFilterConditions;
  fields: NestFilterFields;
  isFirst?: boolean;
  isRoot?: boolean;
  showError?: boolean;
  disabled?: boolean;
  defaultFirstItem?: boolean;
  onChange: NestFilterChangeHandler;
  onDelete?: (seq: number) => void;
}

export default Conditions;

const AND: NestFilterJoint = "AND";

function Conditions({
  conditions,
  fields,
  isFirst,
  isRoot,
  joint: propsJoint,
  seq: propsSeq,
  showError,
  disabled,
  defaultFirstItem = true,
  onChange,
}: ConditionArrayProps) {
  const classes = useStyles();

  const newLeaf = () => {
    const firstField = fields[0];
    if (!firstField) {
      const err = "使用高级筛选组件时 fields 参数至少包含一个字段条件";
      message.error(err);
      throw Error(err);
    }
    return {
      joint: AND,
      condition: {
        key: firstField.key,
        operator: getOperatorsByField(firstField)[0].value,
        value: [],
      },
    };
  };

  useEffect(() => {
    //   添加一个默认的搜索选项
    if (defaultFirstItem && isRoot && conditions.length == 0) add();
  }, []);

  const add = () => {
    onChange(propsSeq, propsJoint, [...conditions, newLeaf()]);
  };

  const updateConditionItem = (
    seq: number,
    joint: NestFilterJoint,
    v: NestFilterCondition
  ) => {
    if (joint) conditions[seq].joint = joint;
    let cnd = conditions[seq];
    if (v && "condition" in cnd) cnd.condition = v;
    onChange(propsSeq, propsJoint, [...conditions]);
  };

  const updateConditionArray = (
    seq: number,
    joint: NestFilterJoint,
    v: NestFilterConditions
  ) => {
    // 如果 v 是空数组，那么就不再需要这个选项了
    if (v.length == 0) remove(seq);
    else {
      conditions[seq] = {
        joint: joint,
        conditions: v,
      };
      onChange(propsSeq, propsJoint, [...conditions]);
    }
  };

  const updateJoint = (joint: NestFilterJoint) => {
    onChange(propsSeq, joint, [...conditions]);
  };

  const remove = (seq: number) => {
    conditions.splice(seq, 1);
    onChange(propsSeq, propsJoint, [...conditions]);
  };

  const expand = (seq: number) => {
    conditions[seq] = {
      conditions: [conditions[seq], newLeaf()],
      joint: conditions[seq].joint,
    };
    onChange(propsSeq, propsJoint, [...conditions]);
  };

  return (
    <div className={classes.conditionsPanel}>
      {!isRoot && (
        <div className={classes.joint}>
          {!isFirst && (
            <Joint
              value={propsJoint}
              onChange={updateJoint}
              disabled={disabled}
            />
          )}
        </div>
      )}
      <div
        className={classNames(
          classes.conditionValuePanel,
          !isRoot && classes.conditionBorder
        )}
      >
        <div className={classes.conditionValue}>
          {conditions.map((i, index) => {
            if ("conditions" in i)
              return (
                <Conditions
                  key={index}
                  seq={index}
                  showError={showError}
                  joint={i.joint}
                  fields={fields}
                  conditions={i.conditions}
                  isFirst={index == 0}
                  onChange={updateConditionArray}
                  onDelete={remove}
                  disabled={disabled}
                />
              );
            if ("condition" in i)
              return (
                <ConditionItem
                  key={index + i.condition.key}
                  seq={index}
                  showError={showError}
                  joint={i.joint}
                  condition={i.condition}
                  fields={fields}
                  isFirst={index == 0}
                  disabled={disabled}
                  onChange={updateConditionItem}
                  onDelete={remove}
                  onExpand={expand}
                />
              );
          })}
        </div>
        <Button onClick={add} disabled={disabled}>
          添加条件
        </Button>
      </div>
    </div>
  );
}
